package com.x.erp.dao;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Repository;

import com.x.erp.model.GateCar;
import com.x.framework.dao.BaseDao;

/**
 * 道闸出入车辆信息信息DAO
 */
@Repository
public class GateCarDao extends BaseDao {

	private final static String selectGateCarListSql = "SELECT T1.*, T2.MARKET_NAME FROM ERP_GATE_CAR T1, ERP_MARKET T2 WHERE T1.MARKET_ID = T2.MARKET_ID ";
	/**
	 * 查询道闸出入车辆信息列表
	 * @param gateCar
	 * @return
	 * @throws Exception
	 */
	public List<GateCar> selectGateCarList(GateCar gateCar) throws Exception{
		StringBuilder sql = new StringBuilder(selectGateCarListSql);
		List<Object> params = new ArrayList<Object>();
		searchCondition(sql, params, gateCar);
		sql.append("ORDER BY T1.CAR_CREATE_TIME DESC ");
		return this.queryForList(sql.toString(), GateCar.class, params, gateCar);
	}

	private final static String selectGateCarNumSql = "SELECT COUNT(T1.CAR_ID) FROM ERP_GATE_CAR T1 WHERE 1=1 ";
	/**
	 * 查询道闸出入车辆信息数量
	 * @param gateCar
	 * @return
	 * @throws Exception
	 */
	public int selectGateCarNum(GateCar gateCar) throws Exception{
		StringBuilder sql = new StringBuilder(selectGateCarNumSql);
		List<Object> params = new ArrayList<Object>();
		searchCondition(sql, params, gateCar);
		return this.queryForInt(sql.toString(), params);
	}

	/**
	 * 查询条件
	 * @param sql
	 * @param params
	 * @param gateCar
	 */
	private void searchCondition(StringBuilder sql, List<Object> params, GateCar gateCar) {
		if(gateCar != null) {
			if(StringUtils.isNotEmpty(gateCar.getCarId())){
				sql.append("AND T1.CAR_ID = ? ");
				params.add(gateCar.getCarId());
			}
			if(StringUtils.isNotEmpty(gateCar.getMarketId())){
				sql.append("AND T1.MARKET_ID = ? ");
				params.add(gateCar.getMarketId());
			}
			if(StringUtils.isNotEmpty(gateCar.getGateCode())){
				sql.append("AND T1.GATE_CODE = ? ");
				params.add(gateCar.getGateCode());
			}
			if(StringUtils.isNotEmpty(gateCar.getCarRfid())){
				sql.append("AND T1.CAR_RFID = ? ");
				params.add(gateCar.getCarRfid());
			}
			if(StringUtils.isNotEmpty(gateCar.getCarCard())){
				sql.append("AND T1.CAR_CARD = ? ");
				params.add(gateCar.getCarCard());
			}
			if(this.isNotNull(gateCar.getCarState())){
				sql.append("AND T1.CAR_STATE = ? ");
				params.add(gateCar.getCarState());
			}
			if(gateCar.getStartTime() != null){
				sql.append("AND T1.CAR_CREATE_TIME >= ? ");
				params.add(gateCar.getStartTime());
			}
			if(gateCar.getEndTime() != null){
				sql.append("AND T1.CAR_CREATE_TIME < ? ");
				params.add(gateCar.getEndTime());
			}
		}
	}
}
